package com.xinlong.shop.api.common;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.xinlong.shop.framework.common.R;
import com.xinlong.shop.framework.weixin.config.WeiXinMpConfig;
import com.xinlong.shop.framework.weixin.service.WeiXinMpService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author Sylow
 * @Description
 * @Date: Created in 18:56 2023/1/4
 */
@RestController
@RequestMapping("/buyer/wx/mp")
public class BuyerWeiXinMpController {

     private final WeiXinMpConfig weiXinMpConfig;
     private final WeiXinMpService weiXinMpService;

    private final static Logger logger = LoggerFactory.getLogger(BuyerWeiXinMpController.class);

    public BuyerWeiXinMpController(WeiXinMpConfig weiXinMpConfig, WeiXinMpService weiXinMpService) {
        this.weiXinMpConfig = weiXinMpConfig;
        this.weiXinMpService = weiXinMpService;
    }

    @GetMapping("/jsConfig")
    public R jsConfig(HttpServletRequest request, String path) {
        String nonceStr = IdUtil.simpleUUID();
        String timestamp = String.valueOf(DateUtil.currentSeconds());
        String ticket = weiXinMpService.getTicket();
        String url = request.getHeader("Referer");
        if (StrUtil.isBlank(url)) {
            return null;
        }
        if (StrUtil.isNotBlank(path)) {
            url += path;
        }
        String str = "jsapi_ticket=" + ticket +
                        "&noncestr=" + nonceStr +
                        "&timestamp=" + timestamp +
                        "&url=" + url;

        String signature = DigestUtil.sha1Hex(str);
        logger.debug("加密字符串:" + str);
        logger.debug("签名:" + signature);

        Map map = new HashMap<String, Object>();
        map.put("appid",weiXinMpConfig.getAppid());
        map.put("timestamp",timestamp);
        map.put("nonceStr",nonceStr);
        map.put("signature",signature);
        return R.success(map);
    }
}
